﻿#region Using namespaces

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.IO;
using System.Text;

using BOL.IO;
using BOL.Apps.GeneNetworkBrowser;
#endregion

namespace BOL.Apps.GeneNetworkBrowser.IO
{
    public class GRBReader : IReader<Network>
    {
        #region Private variables

        private FileStream _fs;

        #endregion

        #region Constructors

        public GRBReader(FileStream fs)
        {
            _fs = fs;
        }

        public GRBReader(string path) : this(new FileStream(path, FileMode.Open)) { }

        #endregion

        #region Public methods

        public Network Read()
        {
            string name;
            string description;

            int geneId1, geneId2;
            uint relationType;

            var genes = new Dictionary<int, Gene>();
            var edges = new List<Relation>();

            using (var br = new BinaryReader(_fs))
            {
	            long length = br.BaseStream.Length;

                name = br.ReadString();
                description = br.ReadString();

                while (br.BaseStream.Position < length)
	            {
                    geneId1 = br.ReadInt32();
                    geneId2 = br.ReadInt32();

                    if (!genes.ContainsKey(geneId1))
                        genes.Add(geneId1, new Gene(geneId1));
                    if (!genes.ContainsKey(geneId2))
                        genes.Add(geneId2, new Gene(geneId2));

                    relationType = br.ReadUInt32();
                    edges.Add(new Relation(genes[geneId1], genes[geneId2], relationType));
	            }
            }

            var network = new Network();
            network.AddVerticesAndEdgeRange(edges);

            return network;
        }

        public void Close()
        {
            _fs.Close();
        }

        #endregion
    }
}
